package threading;



import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

class MyThreadPool {
    //阻塞队列用来存放任务
    private BlockingQueue<Runnable> queue= new LinkedBlockingQueue<>();

    //添加任务
    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);
    }

    //创建一个固定线程的线程池
    public MyThreadPool(int n) {
        for (int i = 0; i < n; i++) {
            Thread t = new Thread( () -> {
                try {
                    while (true) {
                        //此处需要线程内部有一个循环，不停的取任务，做任务
                        Runnable runnable = queue.take();
                        runnable.run();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            t.start();
        }
    }
}

public class ThreadDemo25Pool {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool myThreadPool = new MyThreadPool(10);  //创建10个线程
        for (int i = 0; i < 100; i++) {
            int number = i;
            myThreadPool.submit(new Runnable() {   //匿名内部类
                @Override
                public void run() {
                    System.out.println("hello " + number);  //结果是无序的，说明抢占式执行
                }
            });
        }
    }
}
